package net.huashitong.supervision.task.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.sirdc.modules.core.filter.Paging;
import com.sirdc.modules.sys.base.StringPKService;
import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.service.RedisService;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.AppNew.DTO.UserDTO;
import net.huashitong.supervision.insideDuCha.entity.InsideSubTaskEntity;
import net.huashitong.supervision.insideDuCha.filter.InsideSubTaskFilter;
import net.huashitong.supervision.insideDuCha.filter.InsideUserTaskFilter;
import net.huashitong.supervision.insideDuCha.service.InsideSubTaskService;
import net.huashitong.supervision.insideDuCha.service.InsideUserTaskService;
import net.huashitong.supervision.task.entity.SpecialTask;
import net.huashitong.supervision.task.entity.TaskUnit;
import net.huashitong.supervision.task.entity.TaskUser;
import net.huashitong.supervision.task.filter.SpecialTaskFilter;
import net.huashitong.supervision.task.filter.TaskUnitFilter;
import net.huashitong.supervision.task.filter.TaskUserFilter;
import netscape.javascript.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class TaskNewListService {
    public static final Logger log = LoggerFactory.getLogger(TaskNewListService.class);

    @Autowired
    @Lazy
    private TaskMainService taskMainService;
    @Autowired
    @Lazy
    private TaskSubService taskSubService;
    @Autowired
    @Lazy
    private TaskUnitService taskUnitService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SpecialTaskService specialTaskService;
    @Autowired
    private InsideUserTaskService insideUserTaskService;
    @Autowired
    private InsideSubTaskService insideSubTaskService;
    @Autowired
    private TaskUserService taskUserService;



    private List<TaskUnit> getSpecialTask(SpecialTaskFilter filter,int  imp )
    {
        List<TaskUnit> spAddList = new ArrayList<>();

//        SpecialTaskFilter filter = new SpecialTaskFilter();
       // filter.setPaging(filter.getPaging());
        filter.setType(filter.getType());//代签收
        //spfilter.setOverdueDeptId();//自己单位
        if(1==imp)
        {
            filter.setTaskType("2");//重大事项 1 攻坚，2 重点事项

            filter.setOverdueDeptId(filter.getInspectionId());//获取自己单位的。
            filter.setInspectionId(null);
        }else {
            filter.setTaskType("1");//重大事项 1 攻坚，2 重点事项
           // filter.setInspectionId(filter.getInspectionId());
        }

        List<SpecialTask> specialTasks = specialTaskService.queryFilter(filter);
            /*
                设置量
             */

        for (SpecialTask item : specialTasks) {
            TaskUnit taskUnit = new TaskUnit();
            SysUser user = sysUserService.getById(item.getCreateUser());
            String name = "";
            if(ObjectUtils.isNotBlank(user))
            {

                name=user.getName();
            }

            taskUnit.setSysId(item.getSysId());
            taskUnit.setTaskUnitId(item.getSysId());
            taskUnit.setTaskMainName(item.getTaskMainName());
            taskUnit.setTaskSubName(item.getTaskMainName());
            taskUnit.setTaskMainId(item.getTaskMainId());
            taskUnit.setUnitType("3");//督办  重大事项区分督办和承办。
            taskUnit.setTimeRound(item.getTimeRound());
            taskUnit.setTimeLimit(item.getRoundLimit());
            taskUnit.setType(item.getType());
            taskUnit.setCreateUserName(name);
            taskUnit.setImp(imp);
            String strDept="";
            if(1==imp){

                strDept = redisService.get("dept:" + item.getOverdueDeptId());
            }else {
                strDept = redisService.get("dept:" + item.getInspectionId());

            }
            SysDept sysDept = JSONObject.parseObject(strDept, SysDept.class);
            taskUnit.setDeptName(sysDept.getDeptName());
            spAddList.add(taskUnit);

        }
       // Lists.addAll(spAddList);
        return  spAddList;

    }

    /**
     * 普通任务  和重大任务切换  type /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
     * roleid  /**
     *          * 01  县领导
     *          * 02  主要领导
     *          * 03  分管领导
     *          * 04  经办人
     *          */
    public  List<TaskUnit> getNormalTaskList(TaskUnitFilter filter ){
        UserDTO appLoginUser = filter.getUserDTO();
        List<TaskUnit> Lists = new ArrayList<>();

        String userType = SysUserUtils.getUserType();
        String roleId = SysUserUtils.getRoleId();
        String userId  =SysUserUtils.getUserId();
        String deptId = SysUserUtils.getDeptId();

        if(StringUtils.isBlank(userId))
        {
            userType= appLoginUser.getUserType()+"";
            roleId=appLoginUser.getRoleId();
            userId=filter.getLoginerId();
            deptId=filter.getDeptId();
        }

        List<TaskUnit> spAddList = new ArrayList<>();

        List<TaskUnit> taskUnits=new ArrayList<>();

        //特殊任务表去查找重大事项
        if(filter.getImp()==1){
            SpecialTaskFilter spfilter = new SpecialTaskFilter();
            spfilter.setPaging(filter.getPaging());
            if(!"04".equals(roleId)&&StringUtils.isNotBlank(roleId)){
                spfilter.setCreateUser(userId);

            }
            spfilter.setOverdueDeptId(deptId );//临时设置一个值
            spAddList = getSpecialTask(spfilter, 1);
          //  filter.setPaging(spfilter.getPaging());
            Lists.addAll(spAddList);
            if("1".equals(userType)){
                return Lists;
            }

            //批转列表 那人员任务信息
            TaskUserFilter usertaskfilter = new TaskUserFilter();
            usertaskfilter.setUnitUserId(filter.getUserId());

            if(!"04".equals(roleId))
            {
                usertaskfilter.setCreateUser(filter.getCreateUser());
            }
            //type /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
            // status//状态（0未处理，1已批转，2反馈，3退回，4完成 .5已签收）
            usertaskfilter.setImp(filter.getImp());
            usertaskfilter.setStatus(filter.getType());
            List<TaskUser> taskUsers = taskUserService.queryFilter(usertaskfilter);
            List<TaskUnit> unitAddList = new ArrayList<>();
            for (TaskUser taskUser : taskUsers) {
                TaskUnit byId = taskUnitService.getById(taskUser.getTaskUnitId());
                SysUser user = sysUserService.getById(taskUser.getCreateUser());
                TaskUnit taskUnit = new TaskUnit();
                taskUnit.setTaskUnitId(byId.getSysId());
                taskUnit.setSysId(taskUser.getSysId());
                taskUnit.setTaskMainName(byId.getTaskMainName());
                taskUnit.setTaskSubName(byId.getTaskSubName());
                taskUnit.setTaskMainId(byId.getTaskMainId());
                taskUnit.setUnitType(byId.getUnitType());//督办  重大事项区分督办和承办。批转任务
                taskUnit.setTimeRound(byId.getTimeRound());
                taskUnit.setType(taskUser.getStatus());
                taskUnit.setUserId(taskUser.getUnitUserId());
                taskUnit.setDeptName(taskUser.getUserName());
                taskUnit.setCreateUserName(user.getName());
                taskUnit.setTaskSubId(byId.getTaskSubId());
                taskUnit.setCreateUser(byId.getCreateUser());
                taskUnit.setTimeLimit(byId.getTimeLimit());
                unitAddList.add(taskUnit);
            }
            Lists.addAll(unitAddList);

        }
        /**
         * 经办人任务
         */
        if("04".equals(roleId)||"03".equals(roleId))
        {
            List<TaskUnit> operaTaskList = getOperaTaskList(filter);
            Lists.addAll(operaTaskList);
            return Lists;
        }
        /**
         * 查询攻坚任务； 督查组，且主要领导橘色
         */
        List<TaskUnit> gongjianList = new ArrayList<>();
        if ("1".equals(userType)&&"02".equals(roleId)) {

            SpecialTaskFilter spfilter=new SpecialTaskFilter();
            spfilter.setPaging(filter.getPaging());
            int pagesize= filter.getPaging().getPageSize()-spAddList.size();
            filter.getPaging().setPageSize(pagesize);
            spfilter.getPaging().setPageSize(pagesize);
            spfilter.setType(filter.getType());
            spfilter.setInspectionId(deptId );//临时设置一个值
            gongjianList= getSpecialTask(spfilter, 2);
            Lists.addAll(gongjianList);

        }


        /**
         * 单位任务
         */
        int pagesize= filter.getPaging().getPageSize()-spAddList.size()-gongjianList.size();
        filter.getPaging().setPageSize(pagesize);
        if(pagesize<=0)
        {
            return Lists;
        }

        taskUnits = taskUnitService.queryListUnit(filter);
        taskUnits.forEach(taskUnit -> taskUnit.setTaskUnitId(taskUnit.getSysId()));
        //根据子事项分组；
        taskUnits.forEach(taskUnit -> {
            SysUser user = sysUserService.getById(taskUnit.getCreateUser());
            taskUnit.setCreateUserName(user.getName());
        });


        Lists.addAll(taskUnits);




        return Lists;
    }



    /**
     * 经办人的任务
     * @param filter
     * @return
     */
    public  List<TaskUnit> getOperaTaskList(TaskUnitFilter filter ){

        List<TaskUnit> Lists = new ArrayList<>();

       // String userType = SysUserUtils.getUserType();

        List<TaskUnit> spAddList = new ArrayList<>();

        //批转列表 拿 人员任务信息
        TaskUserFilter usertaskfilter = new TaskUserFilter();
        usertaskfilter.setPaging(filter.getPaging());
        usertaskfilter.setUnitUserId(filter.getUserId());

        if (!"04".equals(SysUserUtils.getRoleId())) {
            usertaskfilter.setCreateUser(filter.getCreateUser());
        }
        //type /任务状态(0.待签收,1待反馈,2已反馈,3退回,4完成 。5已签收)
        // status//状态（0未处理，1已批转，2反馈，3退回，4完成 .5已签收）
        usertaskfilter.setImp(filter.getImp());
        usertaskfilter.setStatus(filter.getType());
        List<TaskUser> taskUsers = taskUserService.queryFilter(usertaskfilter);
        filter.setPaging(usertaskfilter.getPaging()
        );
        List<TaskUnit> unitAddList = new ArrayList<>();
        for (TaskUser taskUser : taskUsers) {
            TaskUnit byId = taskUnitService.getById(taskUser.getTaskUnitId());
            SysUser user = sysUserService.getById(taskUser.getCreateUser());
            TaskUnit taskUnit = new TaskUnit();
            taskUnit.setTaskUnitId(byId.getSysId());
            taskUnit.setSysId(taskUser.getSysId());
            taskUnit.setTaskMainName(byId.getTaskMainName());
            taskUnit.setTaskSubName(byId.getTaskSubName());
            taskUnit.setTaskMainId(byId.getTaskMainId());
            taskUnit.setUnitType(byId.getUnitType());//督办  重大事项区分督办和承办。批转任务
            taskUnit.setTimeRound(byId.getTimeRound());
            taskUnit.setType(taskUser.getStatus());
            taskUnit.setUserId(taskUser.getUnitUserId());
            taskUnit.setDeptName(taskUser.getUserName());
            taskUnit.setCreateUserName(user.getName());
            taskUnit.setCreateUser(taskUser.getCreateUser());
            unitAddList.add(taskUnit);
        }
        spAddList.addAll(unitAddList);
        Lists.addAll(spAddList);

        return Lists;
    }

    /**
     * 内部督查任务 2021年08月20日 xxq web
     * @return
     */
    public List<InsideSubTaskFilter> getInsideTask(InsideSubTaskFilter filter){
        //taskState 任务状态  任务状态 0 未查看 1 未反馈，2 已反馈，3 逾期， 4 完成

        InsideUserTaskFilter insideFilter = new InsideUserTaskFilter();
        insideFilter.setTaskState(filter.getTaskState());
        insideFilter.setPaging(filter.getPaging());
        insideFilter.setOrder(filter.getOrder());
        /*
         * 01  县领导
         * 02  主要领导
         * 03  分管领导
         * 04  经办人
         * 主要领导可以查看我创建的内部事项
         */
        String userId = SysUserUtils.getUserId();
        if(StringUtils.isBlank(userId))
        {
            return null;
        }
        if ("02".equals(SysUserUtils.getRoleId())) {
            //主要领导，包含我创建的内部督查任务和 我批转的。
            insideFilter.setUserId(userId);
            insideFilter.setCreateUser(userId);
        }else {
            insideFilter.setUserId(userId);
        }


        List<InsideUserTaskFilter> userlist = insideUserTaskService.getUserlist(insideFilter);
        List<InsideSubTaskFilter> subTaskList = new ArrayList<>();
        for (InsideUserTaskFilter item : userlist) {
            String subTaskId = item.getSubTaskId();
            InsideSubTaskEntity subTask = insideSubTaskService.getById(subTaskId);
            SysUser user = sysUserService.getById(item.getCreateUser());
            InsideSubTaskFilter  data = new InsideSubTaskFilter();
            data.setUserId(item.getUserId());
            data.setSubTaskName(subTask.getSubTaskName());
            data.setTaskMainId(item.getMainTaskId());
            data.setUserTaskId(item.getSysId());
            data.setCycleValue(subTask.getCycleValue());
            data.setTimeType(subTask.getTimeType());
            data.setDeptId(item.getDeptId());
            data.setUserName(item.getUserName());
            data.setTaskState(item.getTaskState());
            data.setSysId(item.getSubTaskId());
            data.setCreateUserName(user.getName());
            data.setTimeRound(item.getTimeRound());
            data.setRemindDate(item.getRemindDate());
            subTaskList.add(data);

        }

        return subTaskList;
    }



}
